﻿using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace com.hebg3.app.zip {
  /**
   * 解压类
   */
  class UnZiper {
      /// <summary>
        /// 解压功能(解压压缩文件到指定目录)
        /// </summary>
        /// <param name="FileToUpZip">待解压的文件</param>
        /// <param name="ZipedFolder">指定解压目标目录</param>
        public static void unZip(string fileToUpZip, string zipedFolder, string password){
          //如果要解压的文件不存在,则直接返回
          if (!File.Exists(fileToUpZip)){
              return;
          }
          //如果目标文件夹不存在,则创建
          if (!Directory.Exists(zipedFolder)){
              Directory.CreateDirectory(zipedFolder);
          }

          ZipInputStream s = null;
          ZipEntry theEntry = null;

          string fileName;
          FileStream streamWriter = null;
          try{
            //构建Zip输入流
            s = new ZipInputStream(File.OpenRead(fileToUpZip));
            if(password != null){
              s.Password = password;
            }
            //遍历各个entry
            while ((theEntry = s.GetNextEntry()) != null){
              //如果名字不为空
              if (theEntry.Name != String.Empty){
                //得到文件名
                fileName = Path.Combine(zipedFolder, theEntry.Name);
                ///判断文件路径是否是文件夹
                if (fileName.EndsWith("/") || fileName.EndsWith("\\")){
                  //如果是文件夹,则创建文件夹,并进入下一Entry的遍历
                  Directory.CreateDirectory(fileName);
                  continue;
                }

                //执行到这一步,一定是文件而不是文件夹,构建目标文件的输出流
                streamWriter = File.Create(fileName);
                int size = 2048;//缓冲区大小
                byte[] data = new byte[2048];//缓冲区
                //写文件
                while (true){
                  //读入文件到缓冲区
                  size = s.Read(data, 0, data.Length);
                  if (size > 0){
                    //将缓冲区内容写到文件
                    streamWriter.Write(data, 0, size);
                  }
                  else{
                    break;
                  }
                }
              }
            }
          }
          finally{
            if (streamWriter != null){
              streamWriter.Close();
              streamWriter = null;
            }
            if (theEntry != null){
              theEntry = null;
            }
            if (s != null){
              s.Close();
              s = null;
            }
            GC.Collect();
            GC.Collect(1);
          }
      }
  }

  }

